package com.nowcoder;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author by lvshh
 * @version 1.0
 * @date 2020/5/8 11:21
 */
public class JUC {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(()->{
            for (int i = 0; i < 60; i++) {
                ticket.sale();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 60; i++) {
                ticket.sale();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 60; i++) {
                ticket.sale();
            }
        },"C").start();
    }
}

class Ticket{
    private int ticket = 50;

    Lock lock = new ReentrantLock();


    public  void sale(){

        lock.lock();//加锁


        try {
            //业务代码
            if (ticket > 0){
                System.out.println(Thread.currentThread().getName() + "卖出了第" + (ticket--) +  "张票，还剩" + ticket + "张票");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();//解锁
        }

    }
}
